const {
  ipcMain,
  BrowserWindow,
  webContents,
  app,
  session,
  Notification,
} = require("electron");
const { createNewWindow } = require("./createNewWindow");
const { updateHandle } = require("./update");
const Store = require("electron-store");
const store = new Store();

var winNameListMap = new Map();
ipcMain.on("fire-event", (event, arg) => {
  switch (arg.event) {
    case "window-min":
      BrowserWindow.getFocusedWindow().minimize();
      break;
    case "window-max":
      let win2 = BrowserWindow.getFocusedWindow();
      if (win2.isMaximized()) {
        win2.restore();
        win2.setContentSize(1360, 910);
        win2.center(); //窗体居中
        win2.webContents.send("restoreMaximize", "restore");
      } else {
        win2.maximize();
        win2.webContents.send("restoreMaximize", "maximize");
      }
      break;
    case "create-new-window":
      try {
        winNameListMap.set(arg.param.windowName, "");
        createNewWindow(arg.param);
      } catch (error) {
        console.log(error);
      }
      break;
    case "windows-param":
      // 指定窗口传参数
      try {
        if (arg.param.targetName != "") {
          let id = store.get(arg.param.targetName);
          webContents.fromId(id).send("request-windows-param", arg.param);
        }
        if (arg.param.targetParent != undefined) {
          for (let key of winNameListMap.keys()) {
            if (key.indexOf(arg.param.targetParent) != -1) {
              let id = store.get(key);
              if (webContents.fromId(id) != undefined) {
                webContents
                  .fromId(id)
                  .send("request-windows-param", { emit: "pageRefresh" });
              }
            }
          }
        }
      } catch (error) {
        console.log(error);
      }
      // win.webContents.send('request-windows-param', arg.param);
      break;
    case "windows-home-param":
      ipcMain.send("send-home", arg.param);
      break;
    case "close-windows":
      try {
        let win = BrowserWindow.getFocusedWindow();
        if (arg.param.isQuit == "1") {
          app.quit();
        } else {
          win.close();
        }
      } catch (error) {}
      break;
    case "upload-sys":
      // 更新系统
      let win3 = BrowserWindow.getFocusedWindow();
      updateHandle(win3, arg.param.updateUrl)
        .checkForUpdates()
        .catch((err) => {
          console.log(err);
        });
      // autoUpdater.checkForUpdates();
      break;
    default:
      break;
  }
});
